import time
# 导入token验证函数
from common.token_dec import *
# 导入商品处理函数
from common.goods.get_goods import *
# 导入模型类
from .models import *
# 导入用户模型类
from users.models import *
# 导入商品模型类
from goods.models import *
# 导入响应数据函数
from common.respond.res import res
from django.core.paginator import Paginator  # 这个是处理分页的
from django.forms import model_to_dict  # 这个是转字典的，要是不导入这个的话，接口返回json的时候会报错


# Create your views here.

# 获取登录用户信息
@token_admin_dec
def get_user_info(request):
    # 获取当前token用户对象
    user = request.myuser
    # 将明文密码清空
    user['passStr'] = ''
    # 未获取数据
    if not user:
        return res(400, "获取失败！", {"err": "用户获取失败，请稍后再试！"})
    # 获取成功
    return res(200, "获取成功！", {"user": user})


# 获取菜单
def get_menu(request):
    # 获取全部菜单分类
    menu_list = list(AdminOneMenu.objects.all().values())
    # 通过遍历获取二级菜单
    for i in menu_list:
        menu_two = list(AdminTwoMenu.objects.filter(order=i['id']).values())
        i['children'] = menu_two
    # 响应数据
    return res(200, "获取成功！", {"menuList": menu_list})


# 获取所有前台用户
def get_all_user(request):
    # 所有用户
    user_list = list(Users.objects.all().values())
    # 用户总数
    total = Users.objects.all().values().count()
    return res(200, "获取成功！", {'userList': user_list, "total": total})


# 通过分页获取所有的商品
def get_goods(request):
    page = request.GET.get('page')  # 获取第几页
    limit = request.GET.get('limit')  # 每页有多少条数据
    print(page, limit)
    # 设置默认值
    if page is None or page == '':
        page = 1
    if limit is None or limit == '':
        limit = 10
    # 所有商品
    goods_list = Goods.objects.all()
    # 对数据进行分页处理
    paginator = Paginator(goods_list, limit)
    page_1 = paginator.get_page(page)
    # 获取到分页的数据
    data_liat = []
    for i in page_1:
        mode_to = model_to_dict(i)
        # 将商品数据进行完善
        item = goods_item(mode_to)
        data_liat.append(item)
    return res(200, "获取成功！", {"goodsList": data_liat, 'count': paginator.count, 'time': int(time.time())})
